<template>
  <section>
    <el-row >
      <el-col :span="8">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText" size="mini" ><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      </el-col>
      <el-col :span="8" style="margin-left: 20px">
        <el-button type="image" size="mini" @click="getCheckedNodes">测试</el-button>
        <el-button type="image" size="mini" @click="saveApi" v-if="btnText === '取消'" :disabled="changeKey.length >0?false:true">保存</el-button>
        <!--<el-button type="image" size="mini" @click="undo" v-if="btnText === '取消'" :disabled="changeKey.length >0?false:true">撤销</el-button>&lt;!&ndash;只有在改变状态后才可用&ndash;&gt;-->
        <el-button type="image" size="mini" @click="editApi">{{btnText}}</el-button>
      </el-col>
    </el-row>
    <el-row style="margin-top: 10px">
      <el-tree :data="tableData" node-key="id" :props="defaultProps" :default-expand-all=false :filter-node-method="filterNode" show-checkbox ref="tree" v-loading :check-strictly="false"
               :default-checked-keys="checkApis"
               @check="handleCheckChange"
               @check-change="checkChange"
               @node-click="nodeClick">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span >{{ data.name?data.name:data.label }}{{data.children.length > 0? ' —— '+data.children.length:''}}</span>
        <span>
        <span style="margin-right:10px">{{ data.description?data.description:'' }}</span>
          <el-button type="text" size="mini" @click="test(node,data)">BTN</el-button>
          <!--//测试用，为了看data和node-->
        </span>
      </span>
      </el-tree>
    </el-row>


  </section>
</template>

<script>
  import { mapActions} from 'vuex'
  import Vue from 'vue'//后续添加属性，需要vue联动
  export default {
    name: "selApi",
    props: ['user'],
    data(){
      return {
        btnText:'编辑',
        disabled:false,
        checkApis:[],//初始化显示
        testCheck:[],
        changeKey:[],//保存时需要的数据
        apiList:[
          {label:'core',name:'核心',children:[]},
          {label:'shreypay',name:'支付',children:[]},
          {label:'message',name:'消息',children:[]},
          {label:'qa',name:'问卷',children:[]},
          {label:'qaType',name:'问卷类型',children:[]},
          {label:'publics',name:'公共',children:[]},
          {label:'his',name:'医疗',children:[]},
          {label:'activity',name:'活动',children:[]},
          {label:'refresh',name:'服务器',children:[]},
        ],
        tableData:null,
        filterText:'',
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    },
    watch: {
      filterText(nv,ov) {
        console.log(nv)
        this.$refs.tree.filter(nv);
      }
    },
    computed:{
    },
    created(){
      console.log(this.user)
      this.checkApis = this.user.userResource.apis
      this.getApiList()
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      getCheckedNodes() {
        console.log(this.$refs.tree.getCheckedNodes());
        console.log(this.$refs.tree.getCheckedKeys());
      },
      handleCheckChange(a, b){
        console.log(a,b)
      },
      nodeClick(a,b,c){
        // console.log(a,b,c)
      },
      checkChange(a,b,c){
        console.log(a)
        console.log(b)
        console.log(c)
        if(a.id){//说明是最后一级
          let d={key:a.id,checked:b}
          let index = this.changeKey.findIndex(c=>c.key === a.id)
          if(index >=0){
            this.changeKey[index].checked=b
          }else {
            this.changeKey.push(d)
          }
        }
        console.log(this.changeKey)
      },
      test(node,data){//测试用，为了看data和node
        console.log(node)
        console.log(data)
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      filter(array){
        let tmp =[]
        array.forEach(a=>{
          let index = tmp.findIndex(i=>i.label === a.label)
          if(index <0){
            tmp.push(a)
          }else {
            tmp[index].children = tmp[index].children.concat(a.children)
          }
        })
        return tmp
      },
      make(res){
        res.forEach(r=>{
          let str = r.uri
          let tmpProps= str.split('/')
          if(tmpProps.length >2){
            let label = tmpProps[1]
            this.apiList.forEach(a=>{
              if(a.label === label){
                let tmp = {label:tmpProps[2],children:[]}
                tmp.children.push({label:str,children:[],id:r.id,description:r.description})
                a.children.push(tmp)
              }
            })
          }
        })
        this.apiList.forEach(a=>{
          a.children = this.filter(a.children)
        })
        //添加disabled属性
        let table = this.addDisabled(this.apiList)
        this.tableData = table
      },
      addDisabled(array){
        array.forEach(a=>{
          if(a.children){
            Vue.set(a,'disabled',true)
          }
          if(a.children.length <=0){
            return
          }
          this.addDisabled(a.children)
        })
        return this.apiList
      },
      editApi(){
        if(this.btnText === '编辑'){
          this.btnText = '取消'
        }else {
          this.btnText = '编辑'
        }
        console.log(this.tableData)
        this.changeDisabled(this.tableData)
      },
      undo(){
        // console.log('操作历史————————————',this.changeKey)
        //获取当前勾选的数组key
        let checkedKeys =this.$refs.tree.getCheckedKeys()
        // console.log(checkedKeys)
        //获取最近一次操作
        let tmp = this.changeKey[0]//最近一次操作
        // console.log(tmp)
        //判断该操作是勾选还是取消
        if(tmp.length>0){
          checkedKeys = this.delCheckedKeys(checkedKeys,tmp,tmp[0].checked)
          // console.log(checkedKeys)
        }else {
          if(tmp.checked === true){ //当前为勾选，需要取消 //在当前勾选的数组中删掉此次操作的key
            let index = checkedKeys.indexOf(tmp.key)
            if(index>=0){
              checkedKeys.splice(index,1)
            }
          }else { //当前为取消,需要增加 //在当前勾选的数组中增加此次操作的key
            checkedKeys.push(tmp.key)
          }
        }
        this.changeKey.splice(0,1)//把本次操作删除
        this.$refs.tree.setCheckedKeys(checkedKeys)//更新勾选界面
      },
      delCheckedKeys(a,b,c){
        // console.log(a)
        // console.log(b)
        b.forEach(i=>{
          let index = a.indexOf(i.key)
          if(index >=0){
            a.splice(index,1)
          }else {
            a.push(i.key)
          }
        })
        // console.log(a)
        return a
      },
      operating(){

      },
      changeDisabled(array){
        array.forEach(a=>{
          if(a.children){
            a.disabled = !a.disabled
          }
          if(a.children.length <=0){
            return
          }
          this.changeDisabled(a.children)
        })
      },
      saveApi(){
        this.setUserApi(this.changeKey)
      },
      setUserApi(array){
        let data = {apiId:array[0].key,userId:this.user.id}
        if(array[0].checked === true){
          data.type = 1
        }else {
          data.type = 0
        }
        this.fetch({name:"setUserApi",data:data})
          .then(res=>{
            console.log(res)
            array.splice(0,1)
            if(array.length>0){
              this.setUserApi(array)
            }else {
              this.changeKey=[]
              this.editApi()
            }
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getApiList(){
        let page = this
        this.fetch({name:"getApiList"})
          .then(res=>{
            this.make(res)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
    }
  }
</script>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    line-height: 25px;
  }
</style>
